package com.gzy.rpsm_admin.controller;

import com.gzy.rpsm_admin.pojo.*;
import com.gzy.rpsm_admin.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;

@RestController
@Api(tags = "用户相关api")
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation(value = "根据账号和密码进行登录操作，只需账号和密码。回个人信息和 token 字符串",
            notes = "<span style='color:red'>模拟操作，密码为明文密码</span>",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", type = "String", required = true),
            @ApiImplicitParam(name = "password", type = "String", required = true)
    })
    @PostMapping("/admin/login")
    public ResponsePojo<ResUser> login(@ApiIgnore LoginUser user) {
        //user.setUser_type((short) 1);
        ResUser result = userService.login(user);
        //相当于 if (result!=null){
        if (Optional.ofNullable(result).isPresent()) {
            return ResponsePojo.success(result);
        } else {
            return ResponsePojo.fail(null, "验证失败");
        }
    }

    @GetMapping("/page/user")
    @ApiOperation(value = "返回用户分页数据")
    @ApiParam
    @ApiImplicitParams({
            @ApiImplicitParam(name="current",value ="当前页面",dataType = "Integer",paramType = "query",defaultValue = "1"),
            @ApiImplicitParam(name="size",value = "页面行数",dataType = "Integer",paramType = "query",defaultValue = "10"),
            @ApiImplicitParam(name="condition",value = "姓名或身份证的查询关键字",dataType = "String" ,paramType = "query"),
            @ApiImplicitParam(name="user_type",value = "用户类型(1、管理员；2、物业；3、业主；)",dataType = "Integer",required = true)
    })
    public ResponsePojo<PageResult<User>> getPage(@RequestParam(defaultValue = "1") Integer current, String condition, @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = true) Integer user_type){
        PageResult<User> users = userService.pageOfUser(current,size,condition,user_type);
        ResponsePojo<PageResult<User>> res = ResponsePojo.success(users);
        return res;
    }

    @GetMapping("/admin/byid")
    @ApiOperation( value="根据 id 查找单个用户",
            notes="<span style='color:red'>根据用户 id 查询用户信息</span>",
            response = User.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({ //非实体类参数
            @ApiImplicitParam(name="id",value ="用户id",dataType = "Integer",paramType = "query")
    })
    @ApiParam //实体类参数
    public ResponsePojo<User> queryById(@RequestParam(required = true) Integer id){
        User u = userService.searchById(id);
        return ResponsePojo.success(u);
    }

    /**
     * 上传头像
     *  问题：
     *  1.参数HttpServletRequest req可以不要
     *  2.图片存储路径path应该要配置到配置文件中
     *  3.返回值的data应该是图片的地址，而不是map
     *  4.失败的信息之间放到message中，而不是data中的map里
     *  5.文档中dataType="_file"不对，应该是paramType="formData"
     */
    @PostMapping("/updateAvatar")
    @ApiOperation(value="更新头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name="multipartFile", value ="上传的文件", paramType = "formData", dataTypeClass = MultipartFile.class, required = true)
    })
    public ResponsePojo<Map<String,String>> updateAvatar(
            @RequestPart MultipartFile multipartFile,
            @RequestParam("id") Integer id, HttpServletRequest req){
        //获取全局对象
        //ServletContext app = req.getServletContext();
        //声明返回值
        Map<String,String> map = new HashMap<String,String>();
        //获取文件名，不同浏览器可能获得完整路径
        String fileName = multipartFile.getOriginalFilename();
        //处理路径，获得文件名
        fileName = fileName.split("\\\\")[0];
        //String path = app.getRealPath("/statics/");//获得服务器文件夹的完整路径
        String path = "D:\\cdivtc\\project2024\\property\\preclass\\rpsm_admin\\images\\";//由于这里没有运行真的tomcat，无法获得真实地址，使用打包的路径
        //获得后缀名
        String sufName = fileName.substring(fileName.lastIndexOf('.')+1);
        //判断后缀名
        if(!("png".equals(sufName) || "svg".equals(sufName) || "gif".equals(sufName)
                || "jpg".equals(sufName))){
            map.put("message","不是图片文件");
            return ResponsePojo.fail(map,"后缀名不是常见图片格式");
        }
        if(multipartFile.getSize() > 500 *1024){
            map.put("message","文件体积太大");
            return ResponsePojo.fail(map,"文件超过500k");
        }
        //确保唯一性，将文件保存时将重命名
        fileName = fileName.length() > 3 ?fileName.substring(0,3) : fileName ;
        fileName = fileName + System.currentTimeMillis() + new Random().nextInt(1000) + "." + sufName;
        try {
            multipartFile.transferTo(new File(path+File.separator,fileName));
        } catch (IOException e) {
            e.printStackTrace();
            map.put("message","IO异常");
            return ResponsePojo.fail(map,e.getMessage());
        }
        //根据路径保存到数据库
        User user = new User();
        user.setUserid(id);
        user.setUser_avatar(fileName);
        userService.updateAvatar(user);
        map.put("message","保存成功");
        return ResponsePojo.success(map);
    }
}
